#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "symbolMgt.h"

#define TABLESIZE 10

/* Définition des types */
int TREE_NODE = 1;
int TREE_STRUCT = 2;

/* Déclaration du type Symbol */
struct Symbol {
   char * name;
   int type;
   void *pointeur;
};
/* Initialisation de la table de symbole */
static struct Symbol symbols[TABLESIZE];
/* Fonction pour insérer un symbole */
int insertInSymbolTable(char * symbolName, int type) {
  int i; 
  /* Test if symbol is present */
  if (isInSymbolTable(symbolName) == 1) {
    fprintf(stderr,"symbolNamed %s already present\n",symbolName);
    return EXIT_FAILURE;
  }
  /* Symbol is NOT present in table */
  else {
    for(i=0;symbols[i].name != NULL;i++);
    /* TODO: test if it worked (aka i <= TABLESIZE) */
    /* We (i) are at the first free symbol */
    /* Allocating size for the name char */
    symbols[i].name = malloc((strlen(symbolName) + 1) * sizeof(char));
    strcpy(symbols[i].name,symbolName);
    /* Setting up type */
    symbols[i].type = type;
    fprintf(stderr,"symbolNamed %s inserted\n",symbolName);
    return EXIT_SUCCESS;
  }
}
int isInSymbolTable( char * symbolName) {
  int i;
  for (i = 0; i < TABLESIZE; i++) {
    if (symbols[i].name == NULL) {
      /* Symbol is empty, so next are too */
      return 0; 
    }
    if (strcmp(symbolName,symbols[i].name) == 0) {
      /* symbol Found ! */
      return 1;
    }
  }
  return 0; /* Symbol not found */
}
void printSymbolTable() {
  int i=0;
  while ((symbols[i].name != NULL) && (i < TABLESIZE)) {
    fprintf(stderr,"Symbol %i : %s (%i) %p\n",i,symbols[i].name,symbols[i].type,symbols[i].pointeur);
    i++;
  }
}
int setRefForSymbolInTable(char *symbolName, void * ref) {
  int i;
  for (i = 0; i < TABLESIZE; i++) {
    if (symbols[i].name == NULL) {
      /* Symbol is empty, so next are too */
      return 0;
    }
    if (strcmp(symbolName,symbols[i].name) == 0) {
      /* symbol Found ! */
      symbols[i].pointeur = ref;
    }
  }
}
void * getRefForSymbolInTable(char * symbolName) {
  int i;
  for (i = 0; i < TABLESIZE; i++) {
    if (symbols[i].name == NULL) {
      /* Symbol is empty, so next are too */
      return 0;
    }
    if (strcmp(symbolName,symbols[i].name) == 0) {
      /* symbol Found ! */
      return symbols[i].pointeur;
    }
  }
}
char * firstTreeStructSymbolName () {
  int i;
  for (i = 0; i < TABLESIZE; i++) {
    if (symbols[i].name == NULL) {
      return "";
    }
    else {
      if (symbols[i].type == TREE_STRUCT) {
        return symbols[i].name;
      }
    }
  }
  return "";
}
